<template>
    <div class="container">
        <!-- ip地址分配cti工号 -->
        <div class="paramsManageMain">
            <el-form :inline="true" :model="formData" class="demo-form-inline" size="small">
                <el-form-item label="电脑IP">
                    <el-input v-model="formData.ipAddr" placeholder="请输入电脑IP"></el-input>
                </el-form-item>
                <el-form-item label="分机号">
                    <el-input v-model="formData.extNo" placeholder="请输入分机号"></el-input>
                </el-form-item>
                <el-form-item label="话机IP">
                    <el-input v-model="formData.phoneIpAddr" placeholder="请输入话机IP"></el-input>
                </el-form-item>
                <el-button
                    type="primary"
                    size="small"
                    icon="el-icon-search"
                    @click="hanlesearch"
                    :loading="searchLoading"
                    class="searchBtn"
                >查询</el-button>
                <el-button
                    type="primary"
                    size="small"
                    icon="el-icon-refresh-right"
                    @click="handleReset"
                    :loading="resetLoading"
                    class="resetBtn"
                >重置</el-button>
            </el-form>
            <div style="margin-bottom: 16px">
                <el-button
                    type="primary"
                    size="small"
                    icon="el-icon-circle-plus-outline"
                    @click="hanlePush"
                >新增</el-button>
                <el-button
                    type="primary"
                    size="small"
                    icon="el-icon-circle-plus-outline"
                    @click="clickImport"
                >批量导入</el-button>
                <el-button
                    type="primary"
                    size="small"
                    icon="el-icon-circle-plus-outline"
                    @click="handleExport"
                >导出</el-button>
                <el-button
                    type="primary"
                    size="small"
                    icon="el-icon-circle-plus-outline"
                    @click="deleteAll"
                >批量删除</el-button>
                <el-button
                    type="primary"
                    size="small"
                    icon="el-icon-download"
                    @click="downloadFile"
                >导入模板下载</el-button>
            </div>
            <el-table
                @selection-change="handleSelectionChange"
                :data="tableData"
                width="100%"
                stripe
                border
                class="heard-bg"
            >
                <el-table-column type="selection"></el-table-column>
                <el-table-column label="电脑IP地址" prop="ipAddr"></el-table-column>
                <el-table-column label="电脑MAC地址" prop="macAddr"></el-table-column>
                <el-table-column label="机器名称" prop="hostName"></el-table-column>
                <el-table-column label="话机IP地址" prop="phoneIpAddr"></el-table-column>
                <el-table-column label="话机MAC地址" prop="phoneMacAddr"></el-table-column>
                <el-table-column label="分机号" prop="extNo" width="100%"></el-table-column>
                <el-table-column label="最近修改时间" prop="updateTime"></el-table-column>
                <!--<el-table-column label="所属职场" v-if="flag" prop="workplaceName"></el-table-column>-->
                <el-table-column label="备注" prop="remark"></el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button
                            type="primary"
                            icon="el-icon-edit"
                            circle
                            @click="handleEdit(scope.row)"
                        />
                        <el-button
                            type="danger"
                            icon="el-icon-delete"
                            circle
                            @click="handleDelete(scope.row)"
                        />
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <div class="pagination">
                <Pagination
                    :hanleChangeCurrentPage="hanleChangeCurrentPage"
                    :handleChangeSize="handleChangeSize"
                    :currentPage="currentPage"
                    :pageSize="pageSize"
                    :total="total"
                />
            </div>
        </div>

        <el-dialog
            v-drag
            :close-on-click-modal="false"
            :visible.sync="Show"
            append-to-body
            center
            width="500px"
        >
            <div slot="title">{{ EditTitle }}</div>
            <el-form
                :model="Edit"
                class="menu-setting"
                label-position="right"
                ref="Edit"
                label-width="110px"
                :rules="formRules"
                size="small"
            >
                <el-form-item label=" 电脑IP" prop="ipAddr">
                    <el-input v-model="Edit.ipAddr" placeholder="请输入" style="width: 200px" />
                </el-form-item>
                <el-form-item label="电脑MAC" prop="macAddr">
                    <el-input v-model="Edit.macAddr" placeholder="请输入" style="width: 200px;" />
                </el-form-item>
                <el-form-item label="机器名称" prop="hostName">
                    <el-input v-model="Edit.hostName" placeholder="请输入" style="width: 200px" />
                </el-form-item>
                <el-form-item label=" 话机IP" prop="phoneIpAddr">
                    <el-input v-model="Edit.phoneIpAddr" placeholder="请输入" style="width: 200px" />
                </el-form-item>
                <el-form-item label="话机MAC" prop="phoneMacAddr">
                    <el-input v-model="Edit.phoneMacAddr" placeholder="请输入" style="width: 200px;" />
                </el-form-item>
                <el-form-item label="分机号" prop="extNo">
                    <el-input v-model="Edit.extNo" placeholder="请输入" style="width: 200px" />
                </el-form-item>
                <!--<el-form-item label="所属职场" v-if="flag" prop="workplaceId">-->
                <!--<el-select-->
                <!--v-model="Edit.workplaceId"-->
                <!--placeholder="请选择所属职场"-->
                <!--style="width: 200px"-->
                <!--&gt;-->
                <!--<el-option-->
                <!--v-for="item in selectList"-->
                <!--:key="item.id"-->
                <!--:label="item.workplaceName"-->
                <!--:value="item.id"-->
                <!--&gt;</el-option>-->
                <!--</el-select>-->
                <!--</el-form-item>-->
                <el-form-item label="备注">
                    <el-input v-model="Edit.remark" placeholder="请输入" style="width: 200px" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button
                    size="small"
                    icon="el-icon-circle-close"
                    @click="Show = false"
                    class="cancelBtn"
                >取 消</el-button>
                <el-button
                    type="primary"
                    size="small"
                    @click="submitEdit"
                    class="submitBtn"
                    icon="el-icon-circle-check"
                >确定</el-button>
            </div>
        </el-dialog>

        <!--批量导入-->
        <el-dialog
            v-drag
            :close-on-click-modal="false"
            :visible.sync="importShow"
            append-to-body
            center
            width="500px"
            @close="cancelClick"
        >
            <div slot="title">批量导入</div>
            <YsUpload ref="YsUpload" :actionUrl="actionUrl" @getInitData="getInitData"></YsUpload>
            <div slot="footer" class="dialog-footer">
                <el-button
                    size="small"
                    icon="el-icon-circle-close"
                    @click="cancelClick"
                    class="cancelBtn"
                >取 消</el-button>
                <el-button
                    id="importBut"
                    type="primary"
                    size="small"
                    @click="handleImport"
                    class="submitBtn"
                    icon="el-icon-circle-check"
                    :disabled="false"
                >确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import Pagination from '@/components/Pagination/Pagination.vue';
import YsUpload from '@/components/YsUpload/YsUpload.vue';
import { getToken, getTokenHsbankNo } from '@/utils/auth';
import { eachProp } from '@/utils/Object';
import request from '@/apis/request';
import { isNull } from '@/utils/Common';
export default {
    name: 'IpAllocationCti',
    components: {
        Pagination,
        YsUpload,
    },
    data() {
        const validEctNo = (rule, value, callback) => {
            if (value !== '') {
                const params = {
                    lesseeCode: getTokenHsbankNo('HsbankNo'),
                    num: Number(value),
                    numParam: 'EXTENSION_NUM',
                };
                console.log('localStorage');
                callback();
            } else {
                callback(new Error('请输入分机号!'));
            }
        };
        return {
            flag: true,
            formData: {
                ipAddr: '',
                extNo: '',
                phoneIpAddr: '',
            },
            // 新增职场字段
            Edit: {
                workplaceId: '',
                ipAddr: '',
                remark: '',
                paramType: '',
                hostName: '',
                extNo: '',
                macAddr: '',
                phoneIpAddr: '',
                phoneMacAddr: '',
            },
            EditTitle: '',
            Show: false,
            // 搜索loading
            searchLoading: false,
            // 重置loading
            resetLoading: false,
            formRules: {
                ipAddr: [
                    { required: true, message: '请输入电脑IP地址', trigger: 'blur' },
                ],
                macAddr: [
                    { required: true, message: '请输入电脑MAC地址', trigger: 'blur' },
                ],
                extNo: [
                    { required: true, message: '请输入分机号', trigger: 'blur' },
                ],
                phoneIpAddr: [
                    { required: true, message: '请输入话机IP地址', trigger: 'blur' },
                ],
                phoneMacAddr: [
                    { required: true, message: '请输入话机MAC地址', trigger: 'blur' },
                ],
            },
            // 当前页码
            currentPage: 1,
            // 页码大小
            pageSize: 10,
            // 总数
            total: 0,
            // 表格内容
            tableData: [],
            // 下拉数据列表
            selectList: [],
            // 判断新增还是编辑
            ifAddOrUpdate: Boolean,
            importShow: false,
            selections: [],
            actionUrl: '/iccsrv/sys/ip/importIpExtNo',
        };
    },
    mounted() {
        this.getInitData(this.formData);
        if (JSON.parse(getToken()).userType === '1') {
            this.flag = false;
        }
    },
    methods: {
        // 获取参数表格数据
        getInitData(form) {
            let params = {
                pageNum: this.currentPage,
                pageSize: this.pageSize,
            };
            params = Object.assign({}, params, form);
            this.$post.IpAllocation.pageIpExtNo(params)
                .then((res) => {
                    if (res.data.success) {
                        this.tableData = res.data.content.records;
                        this.total = res.data.content.total;
                    }
                });
        },
        // 获取职场下拉选项数据
        getSelectdata() {
            const params = {
                pageNum: 1,
                pageSize: 10,
                lesseeCode: getTokenHsbankNo('HsbankNo'),
            };
            this.$post.Workplace.searchWorkplace(params)
                .then((res) => {
                    console.log(res);
                    if (res.status == 200) {
                        this.selectList = res.data.content.workplaceList;
                    }
                });
        },
        // 点击搜索
        hanlesearch() {
            this.currentPage = 1;
            this.pageSize = 10;
            this.getInitData(this.formData);
        },
        // 点击重置
        handleReset() {
            this.formData = {
                ipAddr: '',
                extNo: '',
                phoneIpAddr: '',
            };
            this.currentPage = 1;
            this.pageSize = 10;
            this.getInitData(this.formData);
        },
        // 点击新增
        hanlePush() {
            this.EditTitle = '添加绑定关系';
            this.Edit = {};
            this.Show = true;
            this.ifAddOrUpdate = true;
            this.Edit.workplaceId = '1';
            // 解决一进来就进行表单验证问题
            if (this.$refs.Edit) {
                this.$refs.Edit.resetFields();
            } else {
                this.$nextTick(() => {
                    // this.$refs.Edit.resetFields();
                });
            }
        },
        // 点击编辑
        handleEdit(row) {
            this.EditTitle = '修改绑定关系';
            this.Edit = JSON.parse(JSON.stringify(row));
            this.Show = true;
            this.ifAddOrUpdate = false;
            if (this.$refs.Edit) {
                this.$refs.Edit.resetFields();
            } else {
                this.$nextTick(() => {
                    // this.$refs.Edit.resetFields();
                });
            }
        },
        // 单个删除职场
        handleDelete(row) {
            this.$confirm('确认删除该绑定关系？', '提示', { customClass: 'warning', type: 'warning' })
                .then(() => {
                    this.$post.IpAllocation.deleteIpExtNo({ id: row.id })
                        .then((res) => {
                            if (res.data.success) {
                                this.$message.success('删除成功！');
                                if (this.tableData.length === 1) {
                                    this.currentPage = this.currentPage - 1;
                                }
                                this.getInitData(this.formData);
                            } else {
                                this.$message.error('删除失败！');
                            }
                        });
                })
                .catch(() => {
                });
        },
        // 新增点击确定按钮
        submitEdit() {
            if (this.ifAddOrUpdate == false) {
                // 编辑
                this.$refs.Edit.validate((valid) => {
                    if (valid) {
                        this.$post.IpAllocation.updateIpExtNo(this.Edit)
                            .then((res) => {
                                if (res.data.success) {
                                    this.$message.success('修改成功！');
                                    this.getInitData(this.formData);
                                    this.Show = false;
                                } else {
                                    this.$message.error(res.data.msg);
                                }
                            });
                    } else {
                        this.$message.warning('请完成表单填写！');
                    }
                });
            } else {
                // 添加
                this.$refs.Edit.validate((valid) => {
                    if (valid) {
                        this.$post.IpAllocation.addIpExtNo(this.Edit)
                            .then((res) => {
                                if (res.data.success) {
                                    this.$message.success('添加成功！');
                                    this.getInitData(this.formData);
                                    this.Show = false;
                                } else {
                                    this.$message.error(res.data.msg);
                                }
                            });
                    } else {
                        this.$message.warning('请完成表单填写！');
                    }
                });
            }
        },
        // 页码切换方法
        hanleChangeCurrentPage(val) {
            this.currentPage = val;
            this.getInitData();
        },
        // 切换分页大小方法
        handleChangeSize(val) {
            this.pageSize = val;
            this.getInitData();
        },
        handleExport() {
            const data = {
                ipAddr: this.formData.ipAddr,
                extNo: this.formData.extNo,
                phoneIpAddr: this.formData.phoneIpAddr,
            };
            let url = '/iccsrv/sys/ip/downloadIpExtNo?';
            eachProp(data, (prop) => {
                if (!isNull(data[prop])) {
                    url += `${prop}=${data[prop].toString()}&`;
                }
            });
            url = url.substring(0, url.length - 1);
            request({
                url,
                method: 'get',
                responseType: 'blob',
            }).then((res) => {
                // console.log(res, '相应报文')
                const blobUrl = window.URL.createObjectURL(new Blob([res.data]));
                const a = document.createElement('a');
                a.style.display = 'none';
                a.download = `话机IP绑定关系表${new Date().getTime()}.xls`;
                a.href = blobUrl;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
            });
        },
        // 点击导入
        clickImport() {
            this.importShow = true;
        },

        // 导入点击确定按钮
        handleImport() {
            this.$refs.YsUpload.submitupload();
        },
        // 取消
        cancelClick() {
            this.$refs.YsUpload.clearFilesFun();
            this.importShow = false;
        },
        downloadFile() {
            const url = '/iccsrv/custlabel/download';
            request({
                url,
                method: 'get',
                responseType: 'blob',
                params: 'ipExtNoTemplate.xlsx',
            }).then((res) => {
                // console.log(res, '相应报文')
                const blobUrl = window.URL.createObjectURL(new Blob([res.data]));
                const a = document.createElement('a');
                a.style.display = 'none';
                a.download = 'ipExtNoTemplate.xlsx';
                a.href = blobUrl;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
            });
        },
        handleSelectionChange(val) {
            console.log("val::::", val);
            this.selections = val;
        },
        deleteAll() {
            console.log("selections::::", this.selections);
            if (this.selections.length <= 0) {
                this.$message.warning('至少选择一项进行删除！');
                return;
            }
            let arr = [];
            this.selections.forEach((item) => {
                arr.push(item.id);
            });
            console.log("arr::::", arr);
            this.$confirm('确认删除所选记录？', '提示', { customClass: 'warning', type: 'warning' })
                .then(() => {
                    this.$post.IpAllocation.deleteIpExtNoAll(arr)
                        .then((res) => {
                            if (res.data.success) {
                                this.$message.success('删除成功！');
                                this.getInitData();
                            } else {
                                this.$message.error('删除失败！');
                            }
                        });
                })
                .catch(() => {
                });
        }
    },
};
</script>

<style  lang="scss">
.container {
    width: 100%;
    height: 100%;
    .paramsManageMain {
        width: 100%;
        background: #fff;
        margin: 0 0 15px;
        // border-radius:5px;
        /* padding: 20px; */
        box-sizing: border-box;
        text-align: left;
        .tableTitle {
            width: 100%;
            height: 48px;
            border: 1px solid #eee;
            border-bottom: none;
            line-height: 48px;
            margin-top: 20px;
            color: #666;
        }
        .pagination {
            margin-top: 20px;
            text-align: right;
        }
    }
}
</style>
